package nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * @Author: KuangJieWen
 * @Date: 2018/3/6 17:06
 * @Description:请在此添加描述
 */
public class NIOServer {
    private Selector selector;

    public void init() throws IOException {
        selector=Selector.open();
        ServerSocketChannel serverSocketChannel=ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);//要设置成非阻塞的，否则会报错
        serverSocketChannel.bind(new InetSocketAddress(9090));
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
    }

    public String write() throws IOException {
        selector.select();
        Iterator<SelectionKey> iterator=selector.selectedKeys().iterator();
        while (iterator.hasNext()){
            SelectionKey selectionKey=iterator.next();
            if(selectionKey.isAcceptable()){
                System.out.println("准备写出信息");
                ServerSocketChannel serverSocketChannel= (ServerSocketChannel) selectionKey.channel();
                SocketChannel socketChannel=serverSocketChannel.accept();
                socketChannel.configureBlocking(false);
                ByteBuffer byteBuffer= ByteBuffer.allocate(1024);
                byteBuffer.put("你已经成功连接".getBytes());
                System.out.println("你已经成功连接".getBytes().length);
                byteBuffer.flip();
                socketChannel.write(byteBuffer);

            }
        }
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "写入成功";
    }

    public static void main(String[] args) throws IOException {
        NIOServer server=new NIOServer();
        server.init();
        System.out.println(server.write());
    }
}
